<template>
<div v-if="this.flowVisible">
	<a-modal
		:title="this.flowTitle"
		:visible="this.flowVisible"
		:width="960"
   		@cancel="cancel"
   		@ok="ok"
	>
	<div id="container"></div>
  </a-modal>
  </div>
</template>

<script>
  import  $ from "jquery"
  import 'jquery-ui/ui/widgets/draggable'
  import 'jquery-ui/ui/widgets/droppable'
  import 'jquery-ui/ui/widgets/resizable'
  import {GETFLOWJSON,SAVEFLOWJSON} from '@/../static/js/apis.js'
  import aModal from "@/common/modal"
  import global from "@/../static/global.vue"
export default{
	inject:['reload'],                                 //注入App里的reload方法
	name: "flowModal",
	props: ['flowTitle', 'flowVisible','id'],
	components: {
		aModal
	},
	data () {
		return {
			jsonData:{}
		}
	},
	created() {
		this.jsPlumb = this.$jsPlumb.getInstance({
			Container:"container",   //选择器id
			EndpointStyle: { radius: 2, fill: "#acd"},  //端点样式
			PaintStyle: { stroke: '#fafafa',strokeWidth:4},// 绘画样式，默认8px线宽  #456
			HoverPaintStyle: { stroke: '#1E90FF'}, // 默认悬停样式  默认为null
			EndpointHoverStyle: { fill: '#acd', radius:4 }, // 端点悬停样式
			ConnectionOverlays:[
				["Arrow",{
					location:1,
					paintStyle: {
						stroke: '#00688B',
						fill: '#00688B',
					}
				}]
			],
			Connector:["Straight",{gap:1}],     //要使用的默认连接器的类型：折线，流程等
			DrapOptions:{cursor:"crosshair",zIndex:2000}
		});
	},
     updated() {
		this.jsPlumb = this.$jsPlumb.getInstance({
			Container:"container",   //选择器id
			EndpointStyle: { radius: 2, fill: "#acd"},  //端点样式
			PaintStyle: { stroke: '#fafafa',strokeWidth:4},// 绘画样式，默认8px线宽  #456
			HoverPaintStyle: { stroke: '#1E90FF'}, // 默认悬停样式  默认为null
			EndpointHoverStyle: { fill: '#acd', radius:4 }, // 端点悬停样式
			ConnectionOverlays:[
				["Arrow",{
					location:1,
					paintStyle: {
						stroke: '#00688B',
						fill: '#00688B',
					}
				}]
			],
			Connector:["Straight",{gap:1}],     //要使用的默认连接器的类型：折线，流程等
			DrapOptions:{cursor:"crosshair",zIndex:2000}
		});
	},
	methods: {
   	 ok(e) {
   	 	let self=this
   	 	  self.getJson()
   	 	  var params={
   	 	  	id:self.id,
   	 	  	editOne:self.jsonData
   	 	  }
	 	  SAVEFLOWJSON(params,function(res){
	 	  	self.$message.success(res.message);
  		     self.$emit("cancel", e)
	       })

      },
      /*关闭modal*/
      cancel(e) {
            this.$emit("cancel", e)
      },
      getJson () {
         var connects = [];
         $.each(this.jsPlumb.getAllConnections(), function (idx, connection) {
	        connects.push({
	            pageSourceId: connection.sourceId,
	            pageTargetId: connection.targetId
	        });
	    });
         var blocks = [];
	    $("#container .node").each(function (idx, elem) {
	           var $elem = $(elem);
                blocks.push({
                    blockName: $elem.text(),
                    type: $elem.attr('type'),
                    blockX: parseInt($elem.css("left")),
                    blockY: parseInt($elem.css("top")),
                    dataId: $elem.attr('id'),
                });
	    });
	    var jsonData={};
	    jsonData.blocks=blocks;
	    jsonData.connects=connects;
         this.jsonData=jsonData
     },
      deleteConnection(){
		   let self=this
		   let ins = self.jsPlumb
		    ins.bind("dblclick", function (conn, originalEvent) {
		        self.$confirm({
		        title: '确定删除此连线吗?',
		        onOk () {
		            ins.deleteConnection(conn);
		        }
		      })
		    });
	 },
      getStaticData(){
      	let self=this
      	var params={
      		id:self.id
      	}
      	self.deleteConnection();
         GETFLOWJSON(params, function (res) {
            var connects = res.obj.connects;
            var blocks = res.obj.blocks;
            var htmlText = "";
            var viewstyle,viewName,viewParam,viewId,viewType;
           for (var i = 0; i < blocks.length; i++){
                viewstyle = 'left:' + blocks[i].blockX + 'px;top:' + blocks[i].blockY + 'px;'
                viewName = blocks[i].blockName,
                viewId = blocks[i].dataId,
                viewType = blocks[i].type;
                if(viewType=='circle'){
                    htmlText=
                        '<div class="startNode node"  type="circle" style="'+viewstyle+'position: absolute" id="' + viewId + '" >' + viewName + '</div>';
                    $('#container').append(htmlText)
                }else if(viewType=='square'){
                    htmlText=
                        '<div class="nodeList node"  type="square" style="'+viewstyle+'position: absolute" id="' + viewId + '" >' + viewName + '</div>';
                    $('#container').append(htmlText)
                }
            }
            $("#container .node").each(function (idx, elem) {
                let ins = self.jsPlumb,
                	$elem = $(elem),
                    id = $elem.attr('id');
                ins.addEndpoint(id, { anchors: "Right" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
                ins.addEndpoint(id, { anchors: "Left" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		       ins.addEndpoint(id, { anchors: "Bottom" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		        ins.addEndpoint(id, { anchors: "Top" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		        ins.makeSource(elem,{
				anchor: ["Continuous", {anchorCount:200, shape:"Rectangle"}],
				allowLoopback: false
			});
			ins.makeTarget(elem,{
				anchor: ["Continuous", {anchorCount:200, shape:"Rectangle"}],
				allowLoopback: false
			});
			  $("#" + id).draggable({
		          containment: "this"});
            });
           for (var i = 0; i < connects.length; i++) {
                var PageSourceId = connects[i].pageSourceId,
                    PageTargetId = connects[i].pageTargetId;
                self.jsPlumb.connect({
                    source: PageSourceId,
                    target: PageTargetId,
                    endpoint: ["Dot", { radius: 3 }],  //端点的形状
                    connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
                });
            }
        })
      }
    },
    // created() {
    //   this.getStaticData();
    // },
  }

</script>

<style>
 #container {
    position: relative;
    background: #efefef;
    width: 100%;
    height: 500px;
  }
 #container   .nodeList {
    width: 100px;
    height: 40px;
    line-height: 40px;
    background: lightcyan;
    text-align: center;
    position: absolute;
    border-radius: 10px;
  }
  .startNode,.endNode{
  	width: 60px;
     height: 60px;
     line-height: 60px;
     border-radius: 50%;
     text-align: center;
     background: lightcyan;
     top: 30px;
     position: absolute;
  }
</style>
